import glob
import os
import shutil

from util_ssh import execute_commands
from util_slash import f_win, f_unix
from file_copy import replace_directory_with_copy

left = "8192G_01"
right = "8192G_02"

base_left_path = rf"\\diskstation2\{left}"
base_right_path = rf"\\diskstation2\{right}"

exclude_list = [
    "_gsdata_"
]

nas_driver_mapping = {
        "8192G_01": "/volume4/8192G_01",
        "8192G_02": "/volume2/8192G_02"
    }

if __name__ == "__main__":
    hostname = "diskstation2"
    port = 22
    username = "admin"
    password = "mjm19831119"

    # 比较goodsync目录下的链接和外部的__sync文件数量
    folder_list = glob.glob(f"{base_left_path}\*__sync")
    file_list = glob.glob(f"{base_left_path}\*__sync.*")
    folder_list.extend(file_list)

    symbol_lists = glob.glob(f'{base_left_path}\goodsync\*')
    symbol_lists = list(filter(lambda x: f_unix(x).split("/")[-1] not in exclude_list, symbol_lists))

    symbol_name_lists = [f_unix(x).split("/")[-1] for x in symbol_lists]
    folder_name_lists = [f_unix(x).split("/")[-1] for x in folder_list]

    new_sync_list = list(set(folder_name_lists) - set(symbol_name_lists))
    removed_sync_list = list(set(symbol_name_lists) - set(folder_name_lists))  # 改完名字后符号变无效了，就读不到了，这里是防御性编程
    find_invalid_symbols_command = f"find {nas_driver_mapping[left]}/goodsync/ -type l -xtype l"  # 找到所有无效的符号，默认其是因为外部去除__sync所致
    command_output = execute_commands(hostname, port, username, password, [find_invalid_symbols_command], require_output=True)
    if command_output:
        invalid_symbol_path_list = command_output.split("\n")
        invalid_symbol_path_list = [x for x in invalid_symbol_path_list if x]  # 去除最后的空字符
        invalid_symbol_list = []
        for invalid_symbol_path in invalid_symbol_path_list:  # 逐个检查invalid_symbol，如果有对应的去除__sync的文件，则代表是手工取消同步的文件，否则是因为其他问题导致，不能盲目认为是取消同步
            if os.path.exists(invalid_symbol_path.rstrip("__sync")):
                invalid_symbol_list.append(f_unix(invalid_symbol_path).split("/")[-1])
            else:
                print(f"error: 不合理的无效链接: {invalid_symbol_path}")

        # invalid_symbol_list = [f_unix(x).split("/")[-1] for x in invalid_symbol_path_list if x]

        removed_sync_list.extend(invalid_symbol_list)

    # 外部__sync多，那么提示手动将文件复制过去
    if len(new_sync_list) > 0:
        # folder_path_list = [os.path.join(base_left_path, x) for x in left]
        ln_command_list = []
        for folder_name in new_sync_list:
            replace_directory_with_copy(os.path.join(base_left_path, folder_name), os.path.join(base_right_path, folder_name), real_delete=False)
            ln_command_list.append(f"ln -s {nas_driver_mapping[left]}/{folder_name} {nas_driver_mapping[left]}/goodsync/{folder_name}")
            ln_command_list.append(f"ln -s {nas_driver_mapping[right]}/{folder_name} {nas_driver_mapping[right]}/goodsync/{folder_name}")
        execute_commands(hostname, port, username, password, ln_command_list)
    # 外部__sync少，那么需要将少的文件，远端也进行操作
    if len(removed_sync_list) > 0:
        unlink_command_list = []
        for folder_name in removed_sync_list:
            # 这里左边因为是已经手工改过名，去除了__sync后缀，所以左边的符号链接已经是无效的了，但是右边的符号仍然是有效的。所以先要unlink，再对右边的文件改名。
            unlink_command_list.append(f"find {nas_driver_mapping[left]}/goodsync/{folder_name} -type l -delete")
            unlink_command_list.append(f"find {nas_driver_mapping[right]}/goodsync/{folder_name} -type l -delete")
        execute_commands(hostname, port, username, password, unlink_command_list)
        # 对右边的文件进行改名
        for folder_name in removed_sync_list:
            # shutil.move(os.path.join(base_right_path, folder_name), os.path.join(base_right_path, folder_name.replace("__sync", "")))
            if os.path.isdir(os.path.join(base_right_path, folder_name)):
                shutil.move(os.path.join(base_right_path, folder_name), os.path.join(base_right_path, folder_name.rstrip("__sync")))
            else:
                shutil.move(os.path.join(base_right_path, folder_name), os.path.join(base_right_path, os.path.splitext(folder_name)[0] + "__sync" + os.path.splitext(folder_name)[1]))

    # 一样多，就没有问题，什么也不用干，提示可以启动goodsync开始正式同步
    if len(folder_name_lists) == len(symbol_name_lists) and len(new_sync_list) == 0 and len(removed_sync_list) == 0:
        print("没有新增或删除，可以直接使用goodsync开始同步")
    pass